package com.young.mylib.utils;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;

/**
 * Created by Young on 2017/3/28.
 */

public class JsonUtils {
    private static final SerializeConfig config;

    static {
        config = new SerializeConfig();
        config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
        config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
    }

    public static JSONObject toJsonObject(String str) {
        try {
            return JSON.parseObject(str);
        } catch (Exception e) {
            Log.e("JsonUtils", "toJson error: " + e.getMessage());
            return null;
        }
    }
    public static JSONArray toJsonArray(String str) {
        try {
            return JSON.parseArray(str);
        } catch (Exception e) {
            Log.e("JsonUtils", "toJson error: " + e.getMessage());
            return null;
        }
    }
    public static String toJSONString(Object object) {
        try {
            return JSON.toJSONString(object);
        } catch (Exception e) {
            return "";
        }

    }

    public static JSONObject toJSON(Object object) {
        try {
            String str = JSON.toJSONString(object);
            return toJsonObject(str);
        } catch (Exception e) {
            return null;
        }

    }

    public static Object getValue(JSONObject json, String key) {
        return json.get(key);
    }

    public static Object toBean(String text) {
        return JSON.parse(text);
    }

    public static <T> T toBean(String text, Class<T> clazz) {
        try {
            return JSON.parseObject(text, clazz);
        } catch (Exception e) {
            return null;
        }

    }

    public static JSONArray getArray(String str) {
        try {
            return JSON.parseArray(str);
        } catch (Exception e) {
            return null;
        }
    }
}
